<?php

use Yaf\Exception\LoadFailed;

/**
 * Class ErrorController
 * @name ErrorController
 * @desc 错误控制器, 在发生未捕获的异常时刻被调用
 * @see http://www.php.net/manual/en/yaf-dispatcher.catchexception.php
 */
class ErrorController extends BaseController
{
    /**
     * 从2.1开始, errorAction支持直接通过参数获取异常
     * @param $exception
     * @return bool
     */
    public function errorAction($exception): bool
    {
        try {
            throw $exception;
        } catch (BadRequestException $ex) {
            // 客户端非法请求
            $code = $ex->getCode();
            $msg = $ex->getMessage();
        } catch (InternalServerErrorException $ex) {
            // 服务器运行异常错误
            $code = $ex->getCode();
            $msg = $ex->getMessage();
        } catch (LoadFailed $ex) {
            // 加载失败
            http_response_code(404);
            $code = $ex->getCode();
            $msg = 'LoadFailed';
        } catch (Exception | Throwable $ex) {
            // 其他异常
            http_response_code(500);
            $code = $ex->getCode();
            $msg = $ex->getMessage();
            file_put_contents(runtime_path() . '/ErrorController.log', __METHOD__ . p($ex, false), FILE_APPEND);
        }

        return $this->json([], $code, $msg);
    }
}
